function TS = insertTS(top, bottom, type)
% insertTS(top, bottom, type) Insert data from TOP into BOTTOM where TOP 
% and BOTTOM are TS structures.  TOP overwrites BOTTOM where applicable and
% leaves BOTTOM as is otherwise.   Set type to '3D' for covariance
% matrices and 'rownames' for TS structures with rownames rather than dates.
% Usage:
%    TS = insertTS(ts1,ts2)
%    TS = insertTS(ts1,ts2,'3D')
%

if nargin < 3; type = ''; end

if isempty(top)
   TS = bottom;
   return
end

[d, top_hdr, btm_hdr] = intersect(top.header, bottom.header);
if ~strcmp(type, 'rownames')
  [d, top_dt, btm_dt] = intersect(top.dates, bottom.dates);
else 
  [d, top_dt, btm_dt] = intersect(top.rownames, bottom.rownames);
end

TS = bottom;

if ndims(top.data) == 3 || strcmp(type, '3D')
   TS.data(btm_hdr, btm_hdr, btm_dt) = top.data(top_hdr, top_hdr, top_dt);
else
   TS.data(btm_dt, btm_hdr) = top.data(top_dt, top_hdr);
end   

return
